<?php
// ************************************************************************
// **                                                                    **
// **          This original software was designed and coded by          **
// **                                                                    **
// **                         David A. Goldsmith                         **
// **                                                                    **
// **                       dave106@wonderdave.com                       **
// **                                                                    **
// **                          March/April 2005                          **
// **                         Revised April 2008                         **
// **                       Revised September 2008                       **
// **                                                                    **
// **                     Revisions for Galileo High School              **
// **                                                                    **
// **                      Doug Piper - piperd@galileoweb.org            **
// **                                                                    **
// **                           September 2009                           **
// **                                                                    **
// ************************************************************************
?>


<html>
    <title>Computer Lab Signup System</title>


    <?php
    include("Configure.php");


    /**
     * Load Zend Frameworks classes
     */
    require_once 'Zend/Loader.php';

    Zend_Loader::loadClass('Zend_Gdata');

    Zend_Loader::loadClass('Zend_Gdata_ClientLogin');

    Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');

    Zend_Loader::loadClass('Zend_Gdata_App_AuthException');

    Zend_Loader::loadClass('Zend_Gdata_App_CaptchaRequiredException');

    Zend_Loader::loadClass('Zend_Http_Client');

    function globalz() {
        // Define and initialize global variables
        global $Date, $Pass, $Room, $Lab, $User, $Invalid;
        $Invalid = 0;
    }

    globalz();
    ?>


    <head>
        <meta http-equiv="Robots" content="none, noarchive">
        <meta http-equiv="Cache-Control" content="no-cache">
        <meta http-equiv="Pragma" content="no-cache">
        <meta http-equiv="Expires" content="-1">
    </head>

    <body bgcolor="#000000" onContextMenu="return false" onDragStart="return false" onSelectStart="return false">


        <?php
        // See if the user has submitted login information
        if (isset($_POST['Submit'])) {
            $User =  mysql_real_escape_string($_POST['User']);
            $Pass = $_POST['Pass'];
            // See if the user login information is valid
            $Invalid = 0;
            $Impersonator = 0;

            // Attempt to retrieve $User from the "LabTeachers" table
            $Query1 = mysql_query("SELECT * FROM LabTeachers WHERE Username='$User'", $DB);
            $NumRecords = mysql_num_rows($Query1);

            if ($NumRecords == 0)
                $Invalid = 5;
            else {
                // Attempt to authenticate the user's credentials with Google Client Login
                // If CaptchaCode is present we are retrying following a server challenge.
                try {
                    if (isset($_POST['CaptchaCode'])) {
                        $client = Zend_Gdata_ClientLogin::getHttpClient($User . $Domain, $Pass,
                                        null, null, null,
                                        $_POST['CaptchaToken'], $_POST['CaptchaCode']);
                    } else {
                        $client = Zend_Gdata_ClientLogin::getHttpClient($User . $Domain, $Pass);
                    }
                } catch (Zend_Gdata_App_CaptchaRequiredException $ce) {
                    $Invalid = 4;
                } catch (Zend_Gdata_App_AuthException $ae) {
                    $Invalid = 1;
                }
            }

            // If the authentication (above) failed, check to see if the person trying to login is actually a
            //  superuser who is trying to (legally) "impersonate" a regular teacher
            // Impersonation turned off pending a less strange implementation.
            if ($Invalid == 99) {
                // Retrieve the usernames for the superuser accounts
                $Query = mysql_query("SELECT Username FROM LabTeachers WHERE Superuser='Y'", $DB);

                while ($Data = mysql_fetch_array($Query)) {
                    try {
                        $client = Zend_Gdata_ClientLogin::getHttpClient($Data["Username"] . $Domain, $Pass,
                                        Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME);
                        $Impersonator = 1;
                        break;
                    } catch (Zend_Gdata_App_AuthException $ae) {
                        if (ereg('Captcha', $ae)) {
                            $Invalid = 4;
                            break;
                        }
                        $Impersonator = 0;
                    } catch (Zend_Gdata_App_Captcha_RequiredException $ce) {
                        $Invalid = 4;
                        break;
                    }
                }
            }

            if (($Invalid == 0) or ($Impersonator == 1)) {
                // Retrieve the information for user $User from the "LabTeachers" table
                $Query1 = mysql_query("SELECT * FROM LabTeachers WHERE Username='$User'", $DB);
                $Data1 = mysql_fetch_array($Query1);
                $NumRecords = mysql_num_rows($Query1);

                // **ToDo*** Discuss if/how to implement auto-enrollment of teachers at Galileo
                // If the user does not already have an account in the "LabTeachers" table, create one now
                //if (($NumRecords == 0) and ($Invalid == 0))
                //{
                //   // Get the user's full name (first and last) from the district's active directory
                //   $UserInfo = ($adLDAP -> user_info($User));
                //   $DisplayName = $UserInfo[0]["displayname"][0];
                //
                //   // From the user's full name ($DisplayName), pull out and separate the first and last names
                //   $TempPos1 = strpos($DisplayName, ",");
                //   $TempPos2 = strrpos($DisplayName, " ");
                //
                //   if ($TempPos1 > 0)
                //   {
                //      $LastName = trim(substr($DisplayName, 0, $TempPos1));
                //      $FirstName = trim(substr($DisplayName, $TempPos1+1));
                //   }
                //   else if ($TempPos2 > 0)
                //   {
                //      $FirstName = trim(substr($DisplayName, 0, $TempPos2));
                //      $LastName = trim(substr($DisplayName, $TempPos2+1));
                //   }
                //
                //   $Query2 = mysql_query("INSERT INTO LabTeachers (Username, LastName, FirstName, Superuser)
                //                          VALUES ('$User', '$LastName', '$FirstName', 'N')", $DB);
                // }
                // Since account information cannot be retrieved for a teacher who is being impersonated,
                //  a superuser can only impersonate a regular teacher if that teacher's account information is
                //  already in the "LabTeachers" table (meaning the teacher has logged in in the past or the
                //  teacher's account data has been previously entered by an administrator)
                if ($NumRecords > 0)
                    $Invalid = 0;
            }


            if ($Invalid == 0) {
                // The user login information IS valid, so record the login in the "LabLogins" table
                $IP = $_SERVER["REMOTE_ADDR"];
                $Query = mysql_query("INSERT INTO LabLogins (Username, Date, Time, IP)
                               VALUES ('$User', CURDATE(), CURTIME(), '$IP')", $DB);


                // Delete all sessions for ANY user from prior to today
                $Query = mysql_query("DELETE FROM LabSessions WHERE Date < CURDATE()", $DB);


                // Delete all sessions for ANY user that have been inactive today for more than $IDLE_TIME minutes
                $Query = mysql_query("DELETE FROM LabSessions WHERE DATE_SUB(NOW(), INTERVAL $IDLE_TIME MINUTE) > Time", $DB);


                // If the user has any previous login session that is still active, erase that session from
                //  the "LabSessions" table
                $Query = mysql_query("DELETE FROM LabSessions WHERE Username='$User'", $DB);


                // Record the user's newly created session in the "LabSessions" table
                $Query = mysql_query("INSERT INTO LabSessions (Username, Date, Time)
                               VALUES ('$User', curdate(), curtime())", $DB);


                // Determine the date of the Monday for this current week (or for the upcoming week, if it is now a weekend)
                $ThisFriday = date("Y-m-d 00:00:00", strtotime("this Friday"));
                $Monday = date("Y-m-d", strtotime("last Monday", strtotime($ThisFriday)));


                // Go through all of the available labs to determine the date of the Monday for the earliest viewable week
                //  that is later than or equal to the week of $Monday (if such a week exists in the "LabSignups" tables)
                $Date = "9999-00-00";

                // Retrieve the room numbers of all of the computer labs from the "Labs" table
                $Query1 = mysql_query("SELECT Room FROM Labs ORDER BY Room DESC", $DB);

                while ($Data1 = mysql_fetch_array($Query1)) {
                    $Lab = $Data1["Room"];
                    $Suffix = str_replace(" ", "_", $Lab);
                    $Query2 = mysql_query("SELECT Date FROM LabSignups$Suffix
                                   WHERE (Date>='$Monday') AND (DAYOFWEEK(Date)=2)
                                   ORDER BY Date", $DB);
                    $Data2 = mysql_fetch_array($Query2);
                    $NumRecords = mysql_num_rows($Query2);

                    if (($NumRecords > 0) and ($Data2["Date"] <= $Date)) {
                        $Room = $Lab;
                        $Date = $Data2["Date"];
                    }
                }


                if (($Room == "") or ($Date == "9999-00-00")) {
                    // A viewable week was NOT found, so display a message to the user
                    echo "<br><br><br><br><br><br><br><center><font face='Arial' size=5 color='#ffff00'><b>";
                    echo "No computer lab weeks are presently available for viewing.";
                    echo "</b></font></center>";
                }
                else
                // A viewable week WAS found, so send the user to the lab signup area (DisplayWeek.php)
                    echo "<body onLoad='document.SignupForm.submit()'>";

                echo "<form name='SignupForm' method='post' action='DisplayWeek.php'>";
                echo "<input type='hidden' name='User' value='$User'>";
                echo "<input type='hidden' name='Room' value='$Room'>";
                echo "<input type='hidden' name='Date' value='$Date'>";
                echo "</form>";
            }
        }

        if ((!(isset($_POST['Submit']))) OR ($Invalid != 0)) {
            // The user login information is NOT valid, or it has not yet been submitted
        ?>

<body onLoad="document.LoginForm.User.focus()">

<table align=center height=90%><tr><td>
    <table align=center width=600 height=400 bgcolor="#D5A7EB" border=0 cellpadding=0 cellspacing=0>
        <tr><td height=16></td></tr>

        <tr valign=top align=left height=96>
            <td width=16></td>

            <td colspan=2 align=left>
                <table width=566 border=0 cellpadding=0 cellspacing=0><tr>
                    <?php
                    include("LoginGraphics.htm");
                    ?>
                </tr></table>
        </td>
    </tr>

    <tr>
        <td width=16></td>

        <td align=center height=240">
            <hr noshade size=3 color="#666666"><br>
            <form name="LoginForm" method="post" action="Login.php">
                <table align=center border=0 cellpadding=0 cellspacing=0><tr>
                        <td><font face="Arial" size=6 color='#000000'><table>
                                    <tr><td height=27><font color='#000000'><b>Username:</b></font></td></tr>
                                    <tr><td height=14></td></tr>
                                    <tr><td height=27><font color='#000000'><b>Password:</b></font></td></tr>
                                </table></font></td>

                        <td width=16></td>

                        <td><table>
                                <?php
                                if ($User)
                                 echo "<tr><td height=27><input type='text' name='User' value=" . $User . " size=30 maxlength=25></td></tr>";
                                else
                                 echo "<tr><td height=27><input type='text' name='User' size=30 maxlength=25></td></tr>";
                                ?>
                                <tr><td height=14 align="right" font color='#000000'><b>@galileoweb.org</b></font></td></tr>
                                <tr><td height=27><input type="password" name="Pass" size=20 maxlength=15></td></tr>
                            </table></td>
                    </tr></table><br>



                <?php
                    if ($Invalid == 0) {
                        echo "<center><font face='Arial' size=5 color='#666666'><b>";
                        echo "Please Login<br>";
                        echo "</b></font></center>";
                    }
                    echo "<center><font face='Arial' size=5 color='#c00000'><b>";
                    if ($Invalid == 1) {
                        echo "Invalid Google Login -- Please try again<br>";
                    }
                    if ($Invalid == 4) {
                        // Deal with captcha challenge raised by Google
                        echo "</b></font></center>";
                        echo "<font face='Arial' size=3 color='#000080'><b>";
                        echo "Please type the characters you see in the picture below<br>";
                        echo "<img src=" . $ce->getCaptchaUrl() . " style='float:center;'><br><br>";
                        echo "<input type='text' name='CaptchaCode' size=30 maxlength=25>";
                        echo "</b></font></a><br><br><br>";
                        echo "<input type='hidden' name='CaptchaToken' value=" . $ce->getCaptchaToken() . ">";                    }
                    if ($Invalid == 5)
                        echo "Unknown teacher -- Please contact an admin<br>";
                    echo "</b></font></center>";
                ?>
                    <center><input type="submit" name="Submit" value="Login"></center>
                </form>
            </td>
            <td width=16></td>
        </tr>
        <tr valign=bottom>
            <td width=16></td>
        </tr>
    </table>
</td></tr></table>
                <?php
                }
                ?>
    </body>
</html>
